package com.aline.ptrscr;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;

public class Controller {

    @FXML
    private Button saveBtn;

    @FXML
    private ComboBox<String> types;

    @FXML
    private CheckBox autoCbx;

    @FXML
    private Label savePath;

    @FXML
    private ComboBox<String> fileNameRule;

    @FXML
    private Button fcBtn;

    private ObservableList<String> comItems = FXCollections.observableArrayList();
    private ObservableList<String> fileNameRuleItem = FXCollections.observableArrayList();

    public void init() {
        comItems.addAll(".png", ".jpeg", ".jpg");
        fileNameRuleItem.addAll(Config.DATETIME_NAME, Config.RANDM_NAME);
        types.setItems(comItems);
        fileNameRule.setItems(fileNameRuleItem);
        boolean autoSave = Config.isAutoSave();
        autoCbx.setSelected(autoSave);
        if (autoSave) {
            changeDisable(!autoSave);
            types.getSelectionModel().select(Config.getType());
            fileNameRule.getSelectionModel().select(Config.getFileNameRule());
            savePath.setText(Config.getSavePath());
        } else {
            types.getSelectionModel().select(0);
            fileNameRule.getSelectionModel().select(0);
            changeDisable(true);
        }
        autoCbx.selectedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                changeDisable(oldValue);
            }
        });
    }

    public void changeDisable(boolean disable) {
        types.setDisable(disable);
        fileNameRule.setDisable(disable);
        fcBtn.setDisable(disable);
    }

    @FXML
    public void chooseFile(ActionEvent event) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("请选择默认保存路径");
        File file = directoryChooser.showDialog(new Stage());
        if (file == null)
            return;
        String path = file.getPath();
        savePath.setText(path);
        Config.setSavePath(path);
    }

    @FXML
    public void saveConf(ActionEvent event) {
        Config.setAutoSave(Boolean.valueOf(autoCbx.isSelected()));
        Config.setFileNameRule(fileNameRule.getSelectionModel().getSelectedItem());
        Config.setSavePath(savePath.getText());
        Config.saveToFile();
    }
}
